"""_summary_
"""
import json
from datetime import datetime, timedelta

from app.api.service import dev_service, img_service, station_service
from app.core.conf import ST
from app.utils.generate_string import get_cur_timestamp
from apscheduler.triggers.date import DateTrigger
from cv.classify.classify_state import ClassifyState
from cv.classify.classify_th import ClassifyTH
from cv.filter.filter import Filter
from cv.image.BaseImg import BaseImg
from loguru import logger
from rasip.camera import get_rasip_photo
from sche_task import schedulerIns
from sche_task.sound import handle_sound
from sche_task.warnings import Warnings
from sio import sio
from sio.agv import send_cvinfo
from sio_agv.agv_socket import AGV
from tornado.limit import Tornado

from .battery import handle_battery_charge
from .camera import handle_nav_status_to_photo
from .error import handle_error_code, handle_warning_code
from .reloc import handle_reloc

connectTornado = Tornado("connect", 3, 10 * 60)


def register_agv_event():
    """定时任务"""
    schedulerIns.add_job(handle_all1_info, "interval", seconds=2, args=[ST.AGV_IP], id=ST.AGV_IP)


async def handle_all1_info(ip):
    """FORK AGV定时任务"""
    try:
        agv = AGV.get_agv(ip)
        agv.send("status", 1, 1100)
        all1 = agv.receive("status")
        save_all1_info(ip, all1)
        change_agv_status(ip, True)
        # 音频处理
        handle_sound(all1)
        # 处理宕机之后的重定位
        handle_reloc(all1.get("reloc_status"), all1.get("x"), all1.get("y"), all1.get("angle"), all1.get("confidence"))
        #  导航完成的拍照任务
        # handle_error_code(all1.get("errors"))
        # handle_warning_code(all1.get("warnings"))
        await handle_nav_status_to_photo(all1)
        # 充电管理
        handle_battery_charge(all1)
        # Warnings.handle(all1.get("warnings"))
    except Exception as e:
        logger.debug(e.args)
        change_agv_status(ip, False)
        handle_agv_disconnect(ip, 15)
        return


def save_all1_info(ip, all1):
    """将all1 info的信息存储起来
    Args:
        all1 (_type_): _description_
        ip (_type_): _description_
    """
    json_str = json.dumps(all1)
    with open(ST.get_all1_info_path(ip), "w", encoding="utf-8") as f:
        f.writelines(json_str + "\n")


def change_agv_status(ip, status):
    """改变AGV的状态
    Args:
        ip (_type_): _description_
        status (_type_): _description_
    """
    with open(ST.AGV_STATUS_PATH, "r", encoding="utf-8") as f:
        content = json.load(f)
    content[ip]["status"] = status
    # 将修改后的字典重新编码为JSON字符串
    json_str = json.dumps(content)
    # 将JSON字符串写入文件
    with open(ST.AGV_STATUS_PATH, "w", encoding="utf-8") as f:
        f.write(json_str)


def handle_agv_disconnect(ip: str, min_num: int):
    """处理AGV断开连接，min分钟后重新连接

    Args:
        ip (str): _description_
        min (int): _description_
    """
    schedulerIns.pause_job(ip)
    run_date = datetime.now() + timedelta(minutes=min_num)
    schedulerIns.add_job(schedulerIns.resume_job, DateTrigger(run_date=run_date), args=[ip], id=f"resume_{ip}")
    logger.warning(f"{ip},断开连接")
    return
